//
//  UIColor+methods.m
//
//
//  Created by 朱旭 on 14/11/26.
//  Copyright (c) 2014年 Zx. All rights reserved.
//

#import "UIColor+methods.h"

@implementation UIColor (methods)

+ (UIColor *)getColorFromRGBString:(NSString *)aString {
    return [self getColorFromRGBString:aString Alpha:1];
}

+ (UIColor *)getColorFromRGBString:(NSString *)aString Alpha:(float)alpha{
    NSString *cString = [[aString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

+ (UIColor *)getColorFromValueRed:(float)red Greed:(float)green Blue:(float)blue Alpha:(float)alpha{
    if (red>=0&&red<=255.0&&green>=0&&green<=255.0&&blue>=0&&blue<=255.0&&alpha>=0&&alpha<=1.0) {
        UIColor * theColor = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha];
        return theColor;
    }
    return 0;
}

+(UIColor *)getRandomColor
{
    CGFloat hue = ( arc4random() % 256 / 256.0 ); //0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0,away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; //0.5 to 1.0,away from black
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}


@end
